package ee.parameterConverter.impl;

import java.lang.reflect.Type;

import ee.parameterConverter.ConversionFailedException;
import ee.parameterConverter.Converter;
import ee.parameterConverter.ConverterResolver;
import ee.parameterConverter.EmptyValueException;
import ee.parameterConverter.SimpleConverter;

public class SimpleConverterImpl implements SimpleConverter {

	private ConverterResolver _converterResolver;

	public SimpleConverterImpl(ConverterResolver converterResolver)
	{
		_converterResolver = converterResolver;
	}
	
	@Override
	public Object convert(String[] value, Type type) throws ConversionFailedException, EmptyValueException {
		// see if we have a converter
		Converter<String[], ?> converter = _converterResolver.getStringArrayConverter(type);

		if (converter == null) {
			throw new ConversionFailedException( 
					"Could not find a converter to convert String[] to " + type + " make sure you register a Converter<String, " + type + "> or Converter<String[], " + type + ">", value);
		}

		return converter.convert(value);
	}
	
	@Override
	public Object convert(String value, Type type) throws ConversionFailedException, EmptyValueException {
		// see if we have a converter
		Converter<String, ?> converter = _converterResolver.getStringConverter(type);
		
		if (converter == null) {
			throw new ConversionFailedException( 
					"Could not find a converter to convert String to " + type + " make sure you register a Converter<String, " + type + ">", value);
		}
		
		return converter.convert(value);
	}
	
}
